package com.lesso.lll.sunflower.device.service.imp;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lesso.lll.sunflower.device.entity.AttendanceDevice;
import com.lesso.lll.sunflower.device.repository.AttendanceDeviceRepository;
import com.lesso.lll.sunflower.device.service.AttendanceDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 考勤设备服务实现类
 */
@Service
public class AttendanceDeviceServiceImpl extends ServiceImpl<AttendanceDeviceRepository, AttendanceDevice> implements AttendanceDeviceService {

    @Autowired
    private AttendanceDeviceRepository deviceRepository;

    @Override
    @Transactional
    public Long addDevice(AttendanceDevice device) {
        // 检查设备编号是否已存在
        AttendanceDevice existDevice = deviceRepository.selectByDeviceId(device.getDeviceId());
        if (existDevice != null) {
            throw new BusinessException("设备编号已存在");
        }

        // 设置默认状态为启用
        device.setStatus(1);
        device.setCreateTime(new Date());
        device.setUpdateTime(new Date());

        // 保存设备信息
        int result = deviceRepository.insert(device);
        if (result > 0) {
            return device.getId();
        }
        return null;
    }

    @Override
    @Transactional
    public boolean updateDevice(AttendanceDevice device) {
        if (device.getId() == null) {
            throw new BusinessException("设备ID不能为空");
        }

        // 更新设备信息
        device.setUpdateTime(new Date());
        int result = deviceRepository.updateById(device);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean deleteDevice(Long deviceId) {
        // 检查设备是否存在
        AttendanceDevice device = deviceRepository.selectById(deviceId);
        if (device == null) {
            throw new BusinessException("设备不存在");
        }

        // 删除设备
        int result = deviceRepository.deleteById(deviceId);
        return result > 0;
    }
}    